package com.lhh.filter;

import cn.hutool.core.util.StrUtil;
import com.lhh.core.Result;
import com.lhh.utils.JsonUtil;
import com.lhh.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;


import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author czx
 * @date 2021/8/15
 */
@CrossOrigin
@WebFilter(urlPatterns = "/user")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getRequestURI().contains("user")) {
            chain.doFilter(request, servletResponse);
            return;
        }
        String tokenHeader = request.getHeader(JwtUtil.TOKEN_HEADER);
        if (StrUtil.isBlank(tokenHeader)) {
            Result result = Result.fail("令牌为空");
            responseJson(response, result, HttpStatus.UNAUTHORIZED.value());
            return;
        }
        if (tokenHeader.startsWith(JwtUtil.TOKEN_PREFIX)) {
            String token = tokenHeader.replace(JwtUtil.TOKEN_PREFIX, "").trim();
            //可能会只传我Bearer 而没有后续的token,要我将这个情况返回401状态码处理
            if (StrUtil.isBlank(token)) {
                Result result = Result.fail("Bearer后面没有令牌");
                responseJson(response, result, HttpStatus.UNAUTHORIZED.value());
                return;
            }
            Claims claims = null;
            try {
                claims = JwtUtil.verifyJwt(token);
            } catch (ExpiredJwtException e) {
                Result result = Result.fail("令牌过期");
                responseJson(response, result, HttpStatus.UNAUTHORIZED.value());
                return;
            } catch (SignatureException e) {
                Result result = Result.fail("令牌无效");
                responseJson(response, result, HttpStatus.UNAUTHORIZED.value());
                return;
            }
            chain.doFilter(request, response);
        } else {
            Result result = Result.fail("非法的令牌开头");
            responseJson(response, result, HttpStatus.UNAUTHORIZED.value());
        }
    }

    /**
     *
     * @param response
     * @param object
     * @param httpStatus
     */
    public static void responseJson(HttpServletResponse response, Object object, int httpStatus) {
        response.setStatus(httpStatus);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try (PrintWriter out = response.getWriter()) {
            String json = JsonUtil.obj2Json(object);
            out.write(json);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
